<?php

namespace addons\csmitsm\library\xcore\xcflow\utils;

use addons\csmitsm\library\sdnode\xstack\utils\XsJsonUtils;
use Error;
use addons\csmitsm\library\xcore\xcore\XcException;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcResponseUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcflowallformUtils;

class XcformFieldsUtils
{
    public static function getAllXcfieldtags($xccontrol)
    {
        $results = [];
        $directory = __DIR__ . '/xcformfields/'. $xccontrol;
        $phpFiles = glob($directory . '/*.php');

        foreach ($phpFiles as $file) {
            $filenameWithoutExtension = pathinfo($file, PATHINFO_FILENAME);
            $results[] = $filenameWithoutExtension;
        }
        return $results;
    }

    /**
     * @return mixed
     */
    public static function createFieldInstance($xccontrol, $xcfieldjsonObj)
    {

        try {
            $clsname = "addons\\csmitsm\\library\\xcore\\xcflow\\utils\\xcformfields\\{$xccontrol}\\" . $xcfieldjsonObj['fieldtag'];
            return new $clsname($xcfieldjsonObj);
        } catch (Error $e) {
            XcResponseUtils::error("控件未实现:" . $xcfieldjsonObj['fieldtag']);
        }
    }

    public static function needPublish($xcformFieldDao, $xcformidFieldname, $xcform_id)
    {
        $list = XcDaoUtils::getListBySql($xcformFieldDao, [
            [$xcformidFieldname, '=', $xcform_id],
            ['haspublish', '<>', 'Y']
        ], null, null, false);

        return count($list) == 0 ? false : true;
    }

    public static function _getXcfieldjsonJsonObjectFromXcform_append($xcform, &$xcfieldjsonObj)
    {
        $tablename = $xcform->publishtablename;
        if (true) {
            $fieldtitle = "id";
            $fieldcode = "id";
            $fieldtag = "xcform_control_objselect";
            array_unshift($xcfieldjsonObj, [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                    "xcform_base_selecttablefield" => ["tablename" => $tablename],
                ])
            ]);
        }
        if (true) {
            $fieldtitle = "user_id";
            $fieldcode = "user_id";
            $fieldtag = "xcform_control_objselect";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                    "xcform_base_selecttablefield" => ["tablename" => XcDatabaseUtils::appendTablePrefix("user"), "showfields" => ["nickname"]],
                ])
            ];
        }

        if (true) {
            $fieldtitle = "创建人";
            $fieldcode = "admin_id";
            $fieldtag = "xcform_control_objselect";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                    "xcform_base_selecttablefield" => ["tablename" => XcDatabaseUtils::appendTablePrefix("admin"), "showfields" => ["nickname"], "filterfields" => ["nickname"]],
                ])
            ];
        }

        if (true) {
            $fieldtitle = "创建时间";
            $fieldcode = "createtime";
            $fieldtag = "xcform_control_input_datetime";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                    "xcform_base_property_input_datetime" => ["format" => 'yyyy-MM-dd HH:mm'],
                ])
            ];
        }

        if (true) {
            $fieldtitle = "修改时间";
            $fieldcode = "updatetime";
            $fieldtag = "xcform_control_input_datetime";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                    "xcform_base_property_input_datetime" => ["format" => 'yyyy-MM-dd HH:mm'],
                ])
            ];
        }

        if (true) {
            $fieldtitle = "排序";
            $fieldcode = "weigh";
            $fieldtag = "xcform_control_input_string";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                ])
            ];
        }

        if (true) {
            $fieldtitle = "状态";
            $fieldcode = "status";
            $fieldtag = "xcform_control_input_string";
            $xcfieldjsonObj[] = [
                'type' => 'system_field',
                'title' => $fieldtitle,
                'fieldcode' => $fieldcode,
                'fieldtag' => $fieldtag,
                'fieldjson' => XsJsonUtils::jsonToString([
                    "__vModel__" => $fieldcode,
                    "__config__" => [
                        "tag" => $fieldtag
                    ],
                    "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                    "xcform_base_xctitle" => ["value" => $fieldtitle],
                    "xcform_prop_hidden" => ["value" => true],
                ])
            ];
        }
    }

    public static function getSimpleXcfieldjsonJsonObjectFromXcform($xcform){
        // $xcfieldjsonObj = json_decode($xcform->xcfieldjson, true);
        $xcfieldjsonObj = XsJsonUtils::stringToJson($xcform->xcfieldjson);
        if ($xcfieldjsonObj == null) {
            $tablename = $xcform->getTable();
            throw new XcException("配置错误", 0, null, "表[{$tablename}]中记录为{$xcform->id}的xcfieldjson字段配置为空或者格式不正确:{$xcform->xcfieldjson}");
        }

        foreach ($xcfieldjsonObj as &$field) {
            $field['type'] = isset($field['type']) ? $field['type'] : 'user_field';
            $field['value'] = null;
            // $field['fieldjsonObj'] = json_decode($field['fieldjson'], true);
            $field['fieldjsonObj'] = XsJsonUtils::stringToJson($field['fieldjson']);
            $field['xcform_id'] = $xcform->id;
            $field['xcformtype'] = XcflowallformUtils::getXcformtypeFromXcform($xcform);
            $field['__vModel__'] = $field['fieldjsonObj']["__vModel__"];
            $xcform->getTable();
        }

        return $xcfieldjsonObj;  
    }

    public static function getXcfieldjsonJsonObjectFromXcform($xcform)
    {
        // $xcfieldjsonObj = json_decode($xcform->xcfieldjson, true);
        $xcfieldjsonObj = XsJsonUtils::stringToJson($xcform->xcfieldjson);
        if ($xcfieldjsonObj == null) {
            $tablename = $xcform->getTable();
            throw new XcException("配置错误", 0, null, "表[{$tablename}]中记录为{$xcform->id}的xcfieldjson字段配置为空或者格式不正确:{$xcform->xcfieldjson}");
        }
        static::_getXcfieldjsonJsonObjectFromXcform_append($xcform, $xcfieldjsonObj);

        foreach ($xcfieldjsonObj as &$field) {
            $field['type'] = isset($field['type']) ? $field['type'] : 'user_field';
            $field['value'] = null;
            // $field['fieldjsonObj'] = json_decode($field['fieldjson'], true);
            $field['fieldjsonObj'] = XsJsonUtils::stringToJson($field['fieldjson']);
            $field['xcform_id'] = $xcform->id;
            $field['xcformtype'] = XcflowallformUtils::getXcformtypeFromXcform($xcform);
            $field['__vModel__'] = $field['fieldjsonObj']["__vModel__"];
            $xcform->getTable();
        }

        return $xcfieldjsonObj;
    }

    // xcfullfieldjsonObj =  xcfieldjsonObj + fieldvalue(from $paramData)
    public static function getXcfullfieldjsonObjFromXcformdataAndXcformdata($xcfieldjsonObj, $xcformdata)
    {
        $xcfieldfulljsonObj = [];
        foreach ($xcfieldjsonObj as $fielditem) {
            $foundFieldValue = null;

            if ($xcformdata != null) {
                foreach ($xcformdata as $fieldcode => $fieldvalue) {
                    if ($fieldcode == $fielditem['fieldcode']) {
                        $foundFieldValue = $fieldvalue;
                        break;
                    }
                }
            }

            $xcfieldfulljsonObj[] = [
                'type' => $fielditem['type'],
                '__vModel__' => $fielditem['fieldjsonObj']['__vModel__'],
                'fieldtitle' => $fielditem['title'],
                'fieldcode' => $fielditem['fieldcode'],
                'fieldtag' => $fielditem['fieldtag'],
                'fieldjsonObj' => $fielditem['fieldjsonObj'],
                'value' => $foundFieldValue,
                // 'config_field_show' => $fielditem['config_field_show'],
                // 'config_field_edit' => $fielditem['config_field_edit'],
                // 'config_field_required' => $fielditem['config_field_required'],
            ];
        }
        return $xcfieldfulljsonObj;
    }

    /**
     * getXcfieldjsonJsonItemFromXcformByFieldcode($xcform, "admin_id");
     * @return json
     */
    public static function getXcfieldjsonJsonItemFromXcformByFieldcode($xcform, $fieldcode)
    {
        $xcfieldjsonObj = static::getXcfieldjsonJsonObjectFromXcform($xcform);
        foreach ($xcfieldjsonObj as $fieldItem) {
            if ($fieldItem["fieldcode"] == $fieldcode) {
                return $fieldItem;
            }
        }
        return null;
    }

    /**
     * xcform_control_value_autono generate while sumbit&null
     * @return void
     */
    public static function processSpecialXcfieldParamsWhilteSumit($xcform, $datarow_id, &$params)
    {
        $xcfieldjsonObj = static::getXcfieldjsonJsonObjectFromXcform($xcform);
        foreach ($xcfieldjsonObj as $field) {
            if ($field['fieldtag'] == 'xcform_control_value_autono') {
                $existNo = null;

                if ($datarow_id != null) {
                    $dataRow = XcformDataUtils::getDbdataByXcformAndRowid($xcform, $datarow_id);
                    $existNo = $dataRow[$field['fieldcode']];
                }

                if ($existNo == null) {
                    $autoCls = XcformFieldsUtils::createFieldInstance("xcform", $field);
                    $existNo = $autoCls->generateDbValue();
                }
                $params[$field['fieldcode']] = $existNo;
            }
        }
    }
}
